package com.shouer.doc.request;

import android.util.Base64;
import android.util.Log;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.shouer.doc.gsonadapter.*;
import java.io.UnsupportedEncodingException;

/**
 * Created by apple on 15/7/18.
 */
public class GsonRequest<T> extends BaseRequest<T> {

    private final Response.Listener<T> mListener;

    private Gson mGson;

    private Class<T> mClass;

    public GsonRequest(Class<T> mClass, Response.Listener<T> mListener, Response.ErrorListener errorListener) {
        super(errorListener);
        initGson();
        this.mClass = mClass;
        this.mListener = mListener;
    }

    public GsonRequest(String methodName, Class<T> mClass, Response.Listener<T> mListener, Response.ErrorListener errorListener) {
        super(methodName, errorListener);
        initGson();
        this.mClass = mClass;
        this.mListener = mListener;
    }

    public GsonRequest(Class<T> mClass, Response.Listener<T> mListener, Response.ErrorListener errorListener, String url) {
        super(errorListener, url);
        initGson();
        this.mClass = mClass;
        this.mListener = mListener;
    }

    public GsonRequest(String url, String methodName, Class<T> mClass, Response.Listener<T> mListener, Response.ErrorListener errorListener) {
        super(url, methodName, errorListener);
        initGson();
        this.mClass = mClass;
        this.mListener = mListener;
    }

    public GsonRequest(int method, String url, Class<T> mClass, Response.Listener<T> mListener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        initGson();
        this.mClass = mClass;
        this.mListener = mListener;
    }

    public GsonRequest(int method, String url, Class<T> mClass, String methodName, Response.Listener<T> mListener, Response.ErrorListener errorListener) {
        super(method, url, methodName, errorListener);
        initGson();
        this.mClass = mClass;
        this.mListener = mListener;
    }

    private void initGson() {
        mGson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().enableComplexMapKeySerialization() //支持Map的key为复杂对象的形式
                .serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")//时间转化为特定格式
                .registerTypeAdapter(Integer.class, new IntegerDefault0Adapter())
                .registerTypeAdapter(int.class, new IntegerDefault0Adapter())
                .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                .registerTypeAdapter(Long.class, new LongDefault0Adapter())
                .registerTypeAdapter(long.class, new LongDefault0Adapter())
                .setPrettyPrinting() //对json结果格式化.
                .setVersion(1.0).create();    //有的字段不是一开始就有的,会随着版本的升级添加进来,那么在进行序列化和返序列化的时候就会根据版本号来选择是否要序列化.@Since(版本号)能完美地实现这个功能.还的字段可能,随着版本的升级而删除,那么@Until(版本号)也能实现这个功能,GsonBuilder.setVersion(double)方法需要调用.  create();
    }


    @Override
    public Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = null;
            if (RequestUtil.NEED_DECRYPT_RESPONSE) {
                long number2 = Long.valueOf(timeStamp);
                int index2 = (int) (number2 % 10);
                String key = RequestUtil.getCryptKey(RequestUtil.getChallenge(index2));
                byte[] decode64 = Base64.decode(response.data, Base64.DEFAULT);
                byte[] decryptBuffer = RequestUtil.AESDecrypt(decode64, key.getBytes());
                jsonString = new String(decryptBuffer,
                        HttpHeaderParser.parseCharset(response.headers));
            } else {

                jsonString = new String(response.data,
                        HttpHeaderParser.parseCharset(response.headers));
            }


            Log.d("接口" + methodName + "返回的数据:", jsonString);
            return Response.success(mGson.fromJson(jsonString, mClass),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            Log.e(GsonRequest.class.getSimpleName(), "parseNetworkResponse():" + e.toString());
            return Response.error(new ParseError(e));
        }
    }

    @Override
    public void deliverResponse(T response) {
        mListener.onResponse(response);
    }
}
